package com.siyoumi.app.modules.book.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.*;
import com.siyoumi.app.modules.book.entity.EnumBookRecordState;
import com.siyoumi.app.modules.book.entity.EnumBookRecordUse;
import com.siyoumi.app.modules.book.service.SvcBook;
import com.siyoumi.app.service.BookRecordService;
import com.siyoumi.app.service.BookSkuDayService;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.IEnum;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xadmin/book/book__record__list")
public class book__record__list
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        InputData inputData = InputData.fromRequest();
        String bookId = inputData.input("book_id");
        String orderType = inputData.input("order_type");

        Book entityBook = SvcBook.getApp().first(bookId);
        if (entityBook == null) {
            return EnumSys.ERR_VAL.getR("预约ID异常");
        }
        setPageTitle(entityBook.getBook_name(), "-预约记录");

        String[] select = {
                "t_book_record.*",
                "book_id",
                "book_name",
                "book_info_json",
                "bsku_name",
                "bday_date",
                "wxuser_nickName",
                "wxuser_unionid",
        };
        JoinWrapperPlus<BookRecord> query = SvcBook.getBean().listRecordQuery(entityBook.getKey(), inputData);
        query.join(Book.table(), Book.tableKey(), "brecord_book_id");
        query.join(BookSkuDay.table(), BookSkuDay.tableKey(), "brecord_bday_id");
        query.join(BookSku.table(), BookSku.tableKey(), "bday_sku_id");
        query.join(WxUser.table(), "wxuser_openid", "brecord_wxuser_id");
        query.select(select);
        query.orderByDesc("brecord_create_date")
                .orderByAsc("brecord_pid");
        query.isNull("brecord_pid");

        IPage<BookRecord> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize());
        //list
        IPage<Map<String, Object>> pageData = BookRecordService.getBean().mapper().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //
        List<Map<String, Object>> listAppend = new ArrayList<>();
        if (!"1".equals(orderType) && list.size() > 0) {
            List<Object> ids = list.stream().map(item -> item.get("brecord_id")).collect(Collectors.toList());

            //同行人订单
            JoinWrapperPlus<BookRecord> queryAppend = BookRecordService.getBean().join();
            queryAppend.select("brecord_id", "brecord_name", "brecord_phone", "brecord_idcard", "brecord_pid", "brecord_create_date");
            queryAppend.in("brecord_pid", ids);
            listAppend = BookRecordService.getBean().getMaps(queryAppend);
            for (Map<String, Object> item : listAppend) {
                itemFor(item);
            }
        }

        long count = pageData.getTotal();

        List<Map<String, Object>> listNew = new ArrayList<>();
        for (Map<String, Object> data : list) {
            String brecordId = (String) data.get("brecord_id");
            itemFor(data);

            listNew.add(data);

            //同行人跟在主订单后面
            if (!"1".equals(orderType)) {
                List<Map<String, Object>> listAppendPid = listAppend.stream()
                        .filter(itemAppend -> itemAppend.get("brecord_pid").equals(brecordId))
                        .collect(Collectors.toList());
                listNew.addAll(listAppendPid);
            }
        }

        if (!isAdminExport()) {
            getR().setData("list", list);
            getR().setData("count", count);

            //使用状态
            setPageInfo("use", IEnum.toMap(EnumBookRecordUse.class));
            //审核状态
            setPageInfo("state", IEnum.toMap(EnumBookRecordState.class));
        } else {
            LinkedMap<String, String> tableHead = new LinkedMap<>();
            tableHead.put("id", "ID");
            tableHead.put("type", "订单类型");
            tableHead.put("brecord_pid", "主订单号");
            tableHead.put("brecord_wxuser_id", "客户openid");
            tableHead.put("wxuser_unionid", "客户unionid");
            tableHead.put("wxuser_nickName", "客户昵称");
            tableHead.put("bday_date", "预约日期");
            tableHead.put("bsku_name", "预约时间段");
            tableHead.put("brecord_name", "姓名");
            tableHead.put("brecord_phone", "手机");
            tableHead.put("brecord_create_date", "预约时间");
            tableHead.put("state", "审核状态");
            tableHead.put("brecord_state_date", "审核时间");
            tableHead.put("use", "使用状态");
            tableHead.put("brecord_use_date", "使用时间");

            List<List<String>> listDataEx = adminExprotData(tableHead, listNew, pageData.getCurrent() == 1);
            getR().setData("list", listDataEx);
        }

        return getR();
    }

    public void itemFor(Map<String, Object> item) {
        BookRecord entity = BookRecordService.getBean().loadEntity(item);
        BookSkuDay entityDay = BookSkuDayService.getBean().loadEntity(item);
        item.put("id", entity.getKey());
        item.put("bday_date", XDate.toDateString(entityDay.getBday_date()));

        Boolean append = XStr.hasAnyText(entity.getBrecord_pid()); //同行人订单
        item.put("append", append);
        item.put("type", append ? "同行人订单" : "主订单");

        item.put("state", IEnum.getEnmuVal(EnumBookRecordState.class, entity.getBrecord_state()));
        item.put("use", IEnum.getEnmuVal(EnumBookRecordUse.class, entity.getBrecord_use()));
    }

    @GetMapping("/export")
    public XReturn export() {
        setAdminExport();
        return index();
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/del")
    public XReturn del() {
        return null;
    }
}
